package com.security.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.security.entity.SecurityUser;
import com.security.entity.User;
import com.security.tool.TokenManager;
import com.security.utils.utils.R;
import com.security.utils.utils.ResponseUtil;
import lombok.SneakyThrows;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

/**
 * @ClassName TokenLoginFilter
 * @Description 认证过滤器
 * @Author liuzhihui
 * @Date 17/3/2021 下午 10:54
 * @Version 1.0
 **/
public class TokenLoginFilter extends UsernamePasswordAuthenticationFilter {
    private TokenManager tokenManager;
    private RedisTemplate redisTemplate;
    private AuthenticationManager authenticationManager;

    public TokenLoginFilter(TokenManager tokenManager, RedisTemplate redisTemplate, AuthenticationManager authenticationManager) {
        this.tokenManager = tokenManager;
        this.redisTemplate = redisTemplate;
        this.authenticationManager = authenticationManager;
        this.setPostOnly(false);
        //会覆盖父类UsernamePasswordAuthenticationFilter设置的super(new AntPathRequestMatcher("/login", "POST"));
        this.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/admin/acl/login","POST"));
//        this.setAuthenticationManager(authenticationManager);
    }

    //获取表单提交过来的用户名和密码
    @SneakyThrows
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException {
        User user = new ObjectMapper().readValue(request.getInputStream(), User.class);

        //把用户名和密码，交给Spring Security进行管理
        //第三个参数是角色权限
        return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user.getUsername(),user.getPassword(),new ArrayList<>()));
    }
    //认证成功后，会调用的方法
    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult)
            throws IOException, ServletException {
        //认证成功后，得到认证成功后的用户信息
        SecurityUser securityUser = (SecurityUser) authResult.getPrincipal();
        //根据用户名生成token
        String token = tokenManager.createToken(securityUser.getCurrentUserInfo().getUsername());
        //把用户名和用户权限列表放到redis
        redisTemplate.opsForValue().set(securityUser.getCurrentUserInfo().getUsername(),securityUser.getPermissionValueList());

        ResponseUtil.out(response, R.ok().data("token",token));
    }
    //认证失败后，会调用的方法
    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed)
            throws IOException, ServletException {
        ResponseUtil.out(response, R.error());
    }
}
